package cn.com.nroad.service.impl;

import cn.com.nroad.domain.Evidence;
import cn.com.nroad.repository.EvidenceJpaRepository;
import cn.com.nroad.service.EvidenceService;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.util.Optional;


@Slf4j
@Service
public class EvidenceServiceImpl implements EvidenceService {

    @Autowired
    private EvidenceJpaRepository evidenceJpaRepository;

    @Value("${file.upload-path}")
    private String rootDir;

    @Override
    public Evidence upload(String name, String uriPath, Long length) {
        Evidence evidence = new Evidence();
        evidence.setName(name);
        evidence.setPath(uriPath);
        evidence.setLength(length);
        String type  = name.substring(name.lastIndexOf("."));
        evidence.setType(type);
        return evidenceJpaRepository.save(evidence);
    }

    @Override
    public Evidence getEvidenceById(String id) {
        if (!StringUtils.isNotBlank(id)){

            throw  new RuntimeException("id is null");
        }
        return evidenceJpaRepository.findById(id).orElseThrow(() -> new RuntimeException("id is not exist"));
    }

    @Override
    public Resource download(String id) {
        String fileUri = evidenceJpaRepository.findById(id).get().getPath();

        log.info("rootDir===" + rootDir);
        String filePath = rootDir + fileUri;
        File file = new File(filePath);
        Path path = file.toPath();
        log.info("path=====" + path.toString());
        try {
            org.springframework.core.io.Resource resource = new UrlResource(path.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                log.error("file not exist: " + fileUri);
                throw  new RuntimeException("file not exist");
            }
        } catch (MalformedURLException e) {
            log.error("Could not read file: " + fileUri);
            throw  new RuntimeException("file not exist");
        }
    }

    @Override
    public void deleteEvidence(String id) {
        Evidence evidence = evidenceJpaRepository.findById(id).orElseThrow(() -> new RuntimeException("id is not exist"));
        String uriPath =evidence.getPath();
        evidenceJpaRepository.delete(id);
        try {
            File file = new File(rootDir+uriPath);
            file.delete();
        } catch (Exception e) {
           log.error("删除佐证失败",e);
        }

    }
}
